#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include <arpa/inet.h>

#define PORT 8088
#define BUFFER_SIZE 1024

int main()
{
    int sock;
    struct sockaddr_in server_address;
    char buffer[BUFFER_SIZE] = {0};

    // 构造 JSON 数据
    const char *json_data =
        "{"
        "  \"problem\": 1,"
        "  \"question\": \"530070070600195000098000060000800006000001260900005000000000000000011111111112222\","
        "  \"answer\": \"530070000600195000098000060000800006000001260900005000204000000000011111111112222\""
        "}";

    // 错误的JSON 数据, 比如里面有数字为字母
    // const char* json_data =
    // "{"
    // "  \"problem\": 1,"
    // "  \"question\": \"5300700706001950000abc00060000800006000001260900005000000000000000011111111112222\","
    // "  \"answer\": \"530070000600195000098000060000800006000001260900005000204000000000011111111112222\""
    // "}";

    // 创建 socket 文件描述符
    if ((sock = socket(AF_INET, SOCK_STREAM, 0)) < 0)
    {
        perror("socket creation failed");
        exit(EXIT_FAILURE);
    }

    // 设置服务器地址
    server_address.sin_family = AF_INET;
    server_address.sin_port = htons(PORT);
    server_address.sin_addr.s_addr = inet_addr("127.0.0.1"); // 服务器的 IP 地址

    // 连接到服务器
    if (connect(sock, (struct sockaddr *)&server_address, sizeof(server_address)) < 0)
    {
        perror("connection to server failed");
        close(sock);
        exit(EXIT_FAILURE);
    }

    printf("Connected to server at port %d\n", PORT);

    // 发送 JSON 数据
    if (send(sock, json_data, strlen(json_data), 0) < 0)
    {
        perror("send failed");
        close(sock);
        exit(EXIT_FAILURE);
    }

    printf("Sent JSON data to server: %s\n", json_data);

    // 接收服务器响应
    int bytes_received = recv(sock, buffer, BUFFER_SIZE, 0);
    if (bytes_received < 0)
    {
        perror("recv failed");
        close(sock);
        exit(EXIT_FAILURE);
    }

    buffer[bytes_received] = '\0'; // 确保字符串以 null 结尾
    printf("Received response from server: %s\n", buffer);

    // 检查服务器响应内容
    if (strstr(buffer, "Invalid JSON data") != NULL)
    {
        printf("Error: Server reported invalid JSON data.\n");
    }
    else
    {
        printf("Server processed the request successfully.\n");
    }

    // 关闭连接
    close(sock);

    return 0;
}